package Z07JDBC.Z08JDBCpool;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 李某
 * * @date 2021/10/21
 * *物有本末，事有终始。知其先后者，则近道矣！
 * *荷花开满池塘的前一天还是半塘荷花半塘云。
 */
public class demp {}




    class ConnectionPool1 {
        List<Connection> cs = new ArrayList<Connection>();
        int size;

        public ConnectionPool1(int size) {
            this.size = size;
            init();
        }

        public void init() {

            //这里恰恰不能使用try-with-resource的方式，因为这些连接都需要是"活"的，不要被自动关闭了
            try {
                Class.forName("com.mysql.jdbc.Driver");
                for (int i = 0; i < size; i++) {
                    Connection c = DriverManager
                            .getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8", "root", "admin");

                    cs.add(c);

                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        public synchronized Connection getConnection() {
            while (cs.isEmpty()) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Connection c = cs.remove(0);
            return c;
        }

        public synchronized void returnConnection(Connection c) {
            cs.add(c);
            this.notifyAll();
        }

    }


